package com.ty.admin.controller;

import com.ty.common.utils.Constant;
import com.wf.captcha.GifCaptcha;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** @author Mjg @QQ:2091864671 @Creates by mjg ON 2020/11/29-21:41 */
@Slf4j
// @CrossOrigin
@RestController
@RequestMapping("admin")
public class CaptchaController {
  @Resource RedisTemplate<String, Object> redisTemplate;

  @GetMapping("/captcha")
  public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
    // 设置请求头为输出图片类型
    response.setContentType("image/gif");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    GifCaptcha captcha = new GifCaptcha(130, 48);
    captcha.setLen(5);
    String code = captcha.text();
    redisTemplate
        .opsForValue()
        .set(Constant.VERIFICATION_CODE, code, 60 * 1000, TimeUnit.MILLISECONDS);
    log.info("运算结果：{}", code);
    try {
      captcha.out(response.getOutputStream()); // 输出验证码
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
